<template>
  <div class="add-address-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="新增地址" left-text="返回" fixed left-arrow @click-left="$router.back()" />

    <!-- 表单区域 -->
    <van-address-edit :area-list="areaList" required show-set-default :area-columns-placeholder="['选择省', '选择市', '选择区/县']" area-placeholder="地区" @save="onSave" />
  </div>
</template>

<script>
import { areaList } from '@vant/area-data'
import axios from '@/utils/request/request'
import { Notify } from 'vant'
export default {
  name: 'addAddress',
  data() {
    return {
      areaList
    }
  },
  methods: {
    // 提交保存
    async onSave(val) {
      this.$toast.loading({
        duration: 0,
        message: '加载中...'
      })
      try {
        const data = await axios.post('/user/add/address', {
          name: val.name,
          phone: val.tel,
          province: val.province,
          city: val.city,
          country: val.county,
          address: val.addressDetail,
          status: val.isDefault ? 1 : 0,
          areacode: val.areaCode
        })
        if (data.code === 0) {
          Notify({ type: 'success', message: data.msg, duration: 1000 })
          this.$router.back()
        } else if (data.code === 403 || data.msg === '身份验证失败') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({ type: 'danger', message: data.msg, duration: 1000 })
        }
      } catch {
        Notify({ type: 'danger', message: '请求失败！', duration: 1000 })
      } finally {
        this.$toast.clear()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.add-address-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 46px;

  ::v-deep .van-switch--on {
    background-color: #0c34ba;
  }
  ::v-deep .van-nav-bar .van-icon,
  ::v-deep .van-nav-bar__text {
    color: #323232;
  }
}
</style>
